/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * OpenMailDlg.java
 *
 * Created on Jun 17, 2009, 9:23:50 PM
 */

package GUI;

import BUS.MailFunctionBUS;
import BUS.StringFunctions;
import DTO.MailStructureDTO;
import java.awt.Cursor;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JEditorPane;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;

/**
 *
 * @author NxSiHMr0D
 */
public class OpenMailDlg extends javax.swing.JFrame {

    /** Creates new form OpenMailDlg */
    public OpenMailDlg() {
        initComponents();
    }
    public OpenMailDlg(MailStructureDTO mail,int row,JTable tb ){
         initComponents();
         _mail = mail;
         rows = row;
         tbListMail = tb;
    }
    MailStructureDTO _mail = new MailStructureDTO();
    int rows;
    JTable tbListMail;
    MailFunctionBUS mailFuncBUS;// = new MailFunctionBUS();
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txtFrom = new javax.swing.JTextField();
        txtSubject = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jPanel4 = new javax.swing.JPanel();
        btReply = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtContentMail = new javax.swing.JEditorPane();

        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Information Mail Receive"));

        jLabel1.setText("From :");

        jLabel2.setText("Subject:");

        jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder("AttachFile"));

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 804, Short.MAX_VALUE)
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 65, Short.MAX_VALUE)
        );

        jScrollPane2.setViewportView(jPanel4);

        btReply.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mail_reply.png"))); // NOI18N
        btReply.setMnemonic('1');
        btReply.setText("Reply");
        btReply.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        btReply.setFocusable(false);
        btReply.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btReply.setPreferredSize(new java.awt.Dimension(40, 73));
        btReply.setSelectedIcon(new javax.swing.ImageIcon(getClass().getResource("/Save.png"))); // NOI18N
        btReply.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btReply.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btReplyActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 53, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtSubject, javax.swing.GroupLayout.DEFAULT_SIZE, 707, Short.MAX_VALUE)
                            .addComponent(txtFrom, javax.swing.GroupLayout.DEFAULT_SIZE, 707, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btReply, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 835, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel2)
                        .addComponent(txtSubject, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(btReply, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(txtFrom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel1)))
                .addGap(23, 23, 23)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 86, Short.MAX_VALUE))
        );

        jScrollPane1.setViewportView(txtContentMail);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 857, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 365, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        try {
            // TODO add your handling code here:
            mailFuncBUS = new MailFunctionBUS();
            txtFrom.setText(_mail.getSender());
            txtSubject.setText(_mail.getTitle());
            String content = _mail.getContentHTML();
            txtContentMail.setEditable(false);
            showAttachFile(rows);
            if (content.equals("")) {
                 txtContentMail.setContentType("text");
                txtContentMail.setText(_mail.getContent());
            } else {
                txtContentMail.setContentType("text/html");
                txtContentMail.setText(_mail.getContentHTML());
            }
            txtContentMail.addHyperlinkListener(new MyHyperlinkListener());
            
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(OpenMailDlg.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SAXException ex) {
            Logger.getLogger(OpenMailDlg.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(OpenMailDlg.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(OpenMailDlg.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_formWindowOpened

    private void btReplyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btReplyActionPerformed
        // TODO add your handling code here:
        FrmSendMailGUI send = new FrmSendMailGUI();
        MailStructureDTO mail = mailFuncBUS.getMail(tbListMail, rows);
        String mailSender = mail.getSender();
        if(mailSender.isEmpty())
        {
            JOptionPane.showMessageDialog(null, "Mail Receiver is not valid");
            return;
        }
        mailSender = StringFunctions.cutStringByChac(mailSender, "<").get(1);
        mailSender = StringFunctions.cutStringByChac(mailSender, ">").get(0);
         send.setSubject("RE: " + mail.getTitle());
        send.setReceiver(mailSender);
        send.show();
    }//GEN-LAST:event_btReplyActionPerformed
     class MyHyperlinkListener implements HyperlinkListener {
        public void hyperlinkUpdate(HyperlinkEvent evt) {
            if (evt.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
                JEditorPane pane = (JEditorPane)evt.getSource();

                    try {
                        // Show the new page in the editor pane.
                        pane.setPage(evt.getURL());
                    } catch (IOException ex) {
                        Logger.getLogger(OpenMailDlg.class.getName()).log(Level.SEVERE, null, ex);
                    }

            }
        }
     }
      private void  showAttachFile(int rows) throws FileNotFoundException{
        ArrayList<File> attachFile = mailFuncBUS.showAttachFile(rows, tbListMail);
         JPanel neo;
         GridLayout layout  = new GridLayout(0, 3);
          neo = new JPanel(layout);
        if (attachFile == null || attachFile.size()==0) {

//            attachFile = new ArrayList<File>();
//            for (int i = 0; i < 4; i++) {
//                attachFile.add(new File(Integer.toString(i)));
//            }

             neo.add(new JLabel(""));
             jScrollPane2.setViewportView(neo);
             return;

        }

        // panel.setPreferredSize(new Dimension(mainView.getWidth()-20,attachFile.size()*30));
        //jScrollPane4.getCo
        JLabel[] labels = new JLabel[attachFile.size()];
       // jScrollPane4.removeAll();

        jScrollPane2.setViewportView(neo);


        for (int index = 0; index < attachFile.size(); index++) {
            labels[index] = new JLabel();
            labels[index].setText(attachFile.get(index).getName());
            //ShellFolder sf;

//                sf = ShellFolder.getShellFolder(attachFile.get(index));
            Icon icon = new ImageIcon("Image\\bullet-red.png");
            labels[index].setIcon(icon);
//                labels[index].setToolTipText(attachFile.get(index).getPath());
            labels[index].addMouseListener(new MouseAdapter() {

                @Override
                public void mousePressed(MouseEvent evt) {
                    try {
                        jLabelMousePressed(evt);
                    } catch (Exception ex) {
                        Logger.getLogger(MainApp.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                @Override
                public void mouseMoved(MouseEvent e) {
                    Cursor tmp = new Cursor( Cursor.HAND_CURSOR);
                    setCursor(tmp);

                }


            });
            neo.add(labels[index]);

        }
        neo.setLayout(layout);
        neo.doLayout();
    }
      private void jLabelMousePressed(MouseEvent evt) throws Exception {
        JLabel label = (JLabel) evt.getComponent();
        String time = label.getText();
        //JOptionPane.showMessageDialog(rootPane, "Xin chao" + time);
        JFileChooser chooserFolder = new JFileChooser();
        chooserFolder.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        if (chooserFolder.showSaveDialog(label) == (int) JFileChooser.APPROVE_OPTION) {
            String folder = chooserFolder.getSelectedFile().getPath();

            if (rows > -1) {

                mailFuncBUS.saveAttachFile(rows, tbListMail, time, folder);
            }
        }
    }


    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new OpenMailDlg().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btReply;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JEditorPane txtContentMail;
    private javax.swing.JTextField txtFrom;
    private javax.swing.JTextField txtSubject;
    // End of variables declaration//GEN-END:variables

}
